package com.noble.meether.chat.ui.imui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.view.menu.MenuBuilder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.bean.my.GiftsList;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.baseui.popup.OptionMenu;
import com.noble.glamour.module.logic.baseui.popup.OptionMenuView;
import com.noble.glamour.module.logic.baseui.popup.PopupMenuView;
import com.noble.glamour.module.logic.socket.NetData;
import com.noble.glamour.module.logic.socket.listener.SendCallBack;
import com.noble.glamour.ui.user.util.OffNetPanel;
import com.noble.imui.chatinput.listener.OnMenuClickListener;
import com.noble.imui.chatinput.model.FileItem;
import com.noble.imui.messagelist.commons.models.IMessage;
import com.noble.imui.messagelist.messages.MsgListAdapter;
import com.noble.imui.messagelist.messages.ptr.PullToRefreshLayout;
import com.noble.library.camera.ImgSelectUtil;
import com.noble.library.dir.DirType;
import com.noble.library.log.PLogger;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.permission.PermissionUtil;
import com.noble.library.utils.BitmapUtil;
import com.noble.library.utils.FileUtil;
import com.noble.meether.MeetUIShow;
import com.noble.meether.R;
import com.noble.meether.chat.MessageConstant;
import com.noble.meether.chat.msgtype.CommonMessage;
import com.noble.meether.chat.msgtype.base.BaseMessage;
import com.noble.meether.chat.ui.agora.RtcUIShow;
import com.noble.meether.chat.ui.agora.dialog.listener.GiftSendListener;
import com.noble.meether.chat.ui.imui.base.IMBaseActivity;
import com.noble.meether.chat.ui.imui.listener.ReceiveMsgListener;
import com.noble.meether.chat.ui.imui.model.DefaultUser;
import com.noble.meether.chat.ui.imui.model.MyMessage;
import com.noble.meether.chat.ui.imui.util.IMChatUtil;
import com.noble.meether.chat.unread.UnreadMgr;
import com.noble.meether.db.callbace.DBQueryCallback;
import com.noble.meether.logic.media.MediaConstant;
import com.noble.meether.logic.media.UpLoadResult;
import com.noble.meether.ui.dialog.MsgTipDialog;
import com.noble.meether.ui.record.RecordVideoAct;
import com.noble.meether.ui.record.Video;
import com.noble.meether.ui.record.VideoPlayDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 聊天界面： 替代 PrivateChatAct
 */
public class IMActivity extends IMBaseActivity implements PObserver, OnMenuClickListener, MsgListAdapter.OnMsgClickListener, ImgSelectUtil.OnChooseCompleteListener, ReceiveMsgListener,
        OptionMenuView.OnOptionMenuClickListener, View.OnClickListener, GiftSendListener {
    public static final String WHISPER_ID = "whisperID";       // 私聊对象ID
    public static final String WHISPER_NAME = "name";          // 私聊对象nickName
    public static final String WHISPER_AVATAR = "avatar";      // 私聊对象头像
    public static final String WHISPER_VIP = "whisperVip";          // 私聊对象vip状态

    private long whisperID = 0;
    private String whisperName;
    private String whisperAvatar;
    private boolean whisperVip;
    private TextView base_title_title;
    private PopupMenuView popup;
    private ImageButton btnSendGift;

    private List<MyMessage> mData = new ArrayList<>();
    private MsgListAdapter<MyMessage> mAdapter;

    private UserDetail userDetail;
    private DefaultUser sendUser;     // 发送方用户信息
    private DefaultUser receiverUser;     // 发送方用户信息

    private MyMessage receiveMessage;
    private MyMessage sendMessage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initMsgAdapter();
        IMChatUtil.getInstance().setReceiveMsgListener(this); // 消息接收回调
    }

    private void initView() {
        userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        whisperID = getIntent().getLongExtra(WHISPER_ID, 0);
        whisperName = getIntent().getStringExtra(WHISPER_NAME);
        whisperAvatar = getIntent().getStringExtra(WHISPER_AVATAR);
        whisperVip = getIntent().getBooleanExtra(WHISPER_VIP, false);
        sendUser = new DefaultUser(String.valueOf(userDetail.getUid()), userDetail.getNickname(), userDetail.getAvatar(), userDetail.isVip());
        receiverUser = new DefaultUser(String.valueOf(whisperID), whisperName, whisperAvatar, whisperVip);

        onTitleInit();
        initFriendStatus();
        // 网络状态提示
        RelativeLayout netStatusLayout = findViewById(R.id.netStatusLayout);
        OffNetPanel offNetPanel = new OffNetPanel(this, netStatusLayout);
        netStatusLayout.addView(offNetPanel);
        chatInputView();  // 初始化输入面板
        MsgMgr.getInstance().attach(this);
        initSendGift();
    }

    private void chatInputView() {
        mChatView.setMenuClickListener(this);
        mChatView.setOnTouchListener(this);
        mChatView.getSelectAlbumBtn().setOnClickListener(view -> ImgSelectUtil.getInstance().pickPhoto(IMActivity.this, IMActivity.this));
    }

    @Override
    protected void onResume() {
        super.onResume();
        UnreadMgr.whisperId = whisperID;
    }

    /**
     * 初始化标题
     */
    @SuppressLint("RestrictedApi")
    private void onTitleInit() {
        setBackView();
        View baseTitleView = LayoutInflater.from(this).inflate(R.layout.title_private_chat, null);
        setTitleCenterContainer(baseTitleView);
        base_title_title = baseTitleView.findViewById(R.id.cus_top_title);
        setNickName(whisperName);

        // pop弹框
        popup = new PopupMenuView(this, R.layout.f1_chat_pop_item);
        popup.inflate(R.menu.menu_im_chat, new MenuBuilder(this));
        popup.setOrientation(LinearLayout.VERTICAL);
        popup.setOnMenuClickListener(this);
        setTitleRightImg(R.drawable.notice_title_more, view -> popup.show(getImgTitleRight()));
    }

    private void setNickName(String nickName) {
        String str = whisperID + "";
        if (!TextUtils.isEmpty(nickName)) {
            str = nickName;
        }
        if (base_title_title != null) {
            base_title_title.setText(str.length() > 10 ? (str.substring(0, 10)) : (str));
        }
    }

    private void initSendGift() {
        btnSendGift = findViewById(R.id.btn_send_gift);
        if (!userDetail.isMan()) {
            btnSendGift.setVisibility(View.GONE);
            return;
        }
        btnSendGift.setOnClickListener(this);
    }

    @Override
    public boolean onOptionMenuClick(int position, OptionMenu menu) {
        if (menu.getId() == R.id.user_blacklist) {
            RtcUIShow.showRtcBlackDlg(this, whisperID);
        }
        if (menu.getId() == R.id.user_delete) {
            MeetUIShow.showMsgTipDlg(this,
                    "确定删除该好友用户吗?", new MsgTipDialog.OnDialogClickListener() {
                        @Override
                        public void onSubmit() {
                            LoadingDialog.show(IMActivity.this, "请稍后...");
                            ModuleMgr.getCommonMgr().setRemoveFriendList(whisperID, response -> {
                                LoadingDialog.closeLoadingDialog(200);
                                if (response.isOk()) {
                                    finish();
                                }
                            });
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
        }
        return true;
    }

    // ================================================= 初始化好友状态 =====================================
    private int statusFriend = -100;                // 好友状态, 默认未成功拿到好友状态

    private void initFriendStatus() {
        ModuleMgr.getCommonMgr().getUserRelation(whisperID, (isOk, status) -> {
            if (!isOk) return;
            statusFriend = status;
        });
    }

    /**
     * 发送消息前预处理
     *
     * @return true: 可正常发消息， false: 不可发消息
     */
    private boolean sendPretreatment() {
        if (statusFriend == 1) {
            return true;
        }

        if (statusFriend == 0 || statusFriend == -2 || statusFriend == -3) {
            MeetUIShow.showMsgTipDlg(this,
                    "您已不是对方好友，是否添加对方为好友?", new MsgTipDialog.OnDialogClickListener() {
                        @Override
                        public void onSubmit() {
                            statusFriend = -1;
                            ModuleMgr.getCommonMgr().setAddFriends(whisperID, null);
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
            return false;
        }

        if (statusFriend == -1) {
            PToast.showShort("好友申请中，暂时无法发送消息");
            return false;
        }

        if (statusFriend == -4) {
            PToast.showShort("您已被对方拉黑，无法进行聊天");
            return false;
        }

        PToast.showShort("好友状态获取失败，暂时无法进行聊天");
        return false;
    }


    // ================================================= 接收消息处理 =====================================
    private CommonMessage receiveMsg;

    @Override
    public void onReceiveMsg(NetData data) {
        receiveMsg = new CommonMessage();
        receiveMsg.parseJson(data.getMsgBody());
        switch (data.getMsgType()) {
            case MessageConstant.MSG_ID_TEXT:       // 文字消息
                receiveMessage = new MyMessage(receiveMsg.getText(), IMessage.MessageType.RECEIVE_TEXT.ordinal());
                receiveMessage.setUserInfo(receiverUser);
                receiveMessage.setMessageStatus(IMessage.MessageStatus.RECEIVE_SUCCEED);
                mAdapter.addToStart(receiveMessage, true);
                break;

            case MessageConstant.MSG_ID_PIC:     // 图片消息
                receiveMessage = new MyMessage(null, IMessage.MessageType.RECEIVE_IMAGE.ordinal());
                receiveMessage.setMediaFilePath(receiveMsg.getImage());
                receiveMessage.setUserInfo(receiverUser);
                receiveMessage.setMessageStatus(IMessage.MessageStatus.RECEIVE_SUCCEED);
                mAdapter.addToStart(receiveMessage, true);
                break;

            case MessageConstant.MSG_ID_VIDEO:      // 小视频消息
                receiveMessage = new MyMessage(null, IMessage.MessageType.RECEIVE_VIDEO.ordinal());
                receiveMessage.setMediaFilePath(receiveMsg.getVideo());
                receiveMessage.setThumbPic(receiveMsg.getThumbPic());
                receiveMessage.setUserInfo(receiverUser);
                receiveMessage.setMessageStatus(IMessage.MessageStatus.RECEIVE_SUCCEED);
                mAdapter.addToStart(receiveMessage, true);
                break;

            case MessageConstant.MSG_ID_GIFT:  // 礼物消息
                receiveMessage = new MyMessage(null, IMessage.MessageType.RECEIVE_GIFT.ordinal());
                receiveMessage.setGiftName(receiveMsg.getGiftName());
                receiveMessage.setGiftIcon(receiveMsg.getGiftIcon());
                receiveMessage.setGiftNum(receiveMsg.getGiftNum());
                receiveMessage.setUserInfo(receiverUser);
                receiveMessage.setMessageStatus(IMessage.MessageStatus.RECEIVE_SUCCEED);
                mAdapter.addToStart(receiveMessage, true);
                break;
        }
    }

    @Override
    public void onReceiveFriendStatusMsg(int msgType) {
        switch (msgType) {
            case MessageConstant.MSG_ADD_BLACK:       // 加入黑名单
                statusFriend = -4;
                receiveMessage = new MyMessage("您已被对方拉黑", IMessage.MessageType.EVENT.ordinal());
                mAdapter.addToStart(receiveMessage, true);
                break;

            case MessageConstant.MSG_DELE_FRIEND:       // 删除好友
                statusFriend = 0;
                receiveMessage = new MyMessage("您已被对方删除好友", IMessage.MessageType.EVENT.ordinal());
                mAdapter.addToStart(receiveMessage, true);
                break;
        }
    }

    @Override
    public void onMessage(String key, Object value) {
    }

    // ===================================================== 读取数据库记录 ===================================================
    private int page = 1;
    private int totalNum = 50;  // 每页查询条数
    private PullToRefreshLayout ptrLayout;
    private CommonMessage dbCommonMessage;
    private MyMessage dbMyMessage;

    private void initMsgAdapter() {
        MsgListAdapter.HoldersConfig holdersConfig = new MsgListAdapter.HoldersConfig();
        mAdapter = new MsgListAdapter<>(String.valueOf(userDetail.getUid()), holdersConfig, getImageLoader());
        mAdapter.setOnMsgClickListener(this);
        mAdapter.setOnAvatarClickListener(null);
        mAdapter.setMsgLongClickListener(null);
        mAdapter.setMsgStatusViewClickListener(null);
        mChatView.setAdapter(mAdapter);
        ptrLayout = mChatView.getPtrLayout();
        ptrLayout.setPtrHandler(layout -> loadNextPage());
        getMessages();
    }

    private void loadNextPage() {
        page++;
        getMessages();
    }

    private void getMessages() {
        try {
            MsgMgr.getInstance().runOnChildThread(this, () -> ModuleMgr.getDbMgr().getMsgCache().queryMsgList(whisperID, totalNum * (page - 1), totalNum, queryCallback));
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
    }

    private DBQueryCallback queryCallback = new DBQueryCallback() {
        @Override
        public void onFailure(int code, String message) {
            ptrLayout.refreshComplete();
        }

        @Override
        public void onSuccess(List<BaseMessage> data) {
            dispatchCacheMessage(data);
            ptrLayout.refreshComplete();
        }
    };

    private void dispatchCacheMessage(List<BaseMessage> data) {
        if (data == null || data.size() <= 0) return;

        int imType;
        mData.clear();
        for (int i = data.size() - 1; i >= 0; i--) {
            BaseMessage tempData = data.get(i);
            dbCommonMessage = new CommonMessage();
            dbCommonMessage.setMsgType(tempData.getMsgType());
            dbCommonMessage.parseContent(tempData.getContent());

            switch (tempData.getMsgType()) {
                case MessageConstant.MSG_ID_TEXT:
                    imType = tempData.isSender() ? IMessage.MessageType.SEND_TEXT.ordinal() : IMessage.MessageType.RECEIVE_TEXT.ordinal();
                    dbMyMessage = new MyMessage(dbCommonMessage.getText(), imType);
                    break;

                case MessageConstant.MSG_ID_PIC:
                    imType = tempData.isSender() ? IMessage.MessageType.SEND_IMAGE.ordinal() : IMessage.MessageType.RECEIVE_IMAGE.ordinal();
                    dbMyMessage = new MyMessage(null, imType);
                    dbMyMessage.setMediaFilePath(dbCommonMessage.getImage());
                    break;

                case MessageConstant.MSG_ID_VIDEO:
                    imType = tempData.isSender() ? IMessage.MessageType.SEND_VIDEO.ordinal() : IMessage.MessageType.RECEIVE_VIDEO.ordinal();
                    dbMyMessage = new MyMessage(null, imType);
                    String videoPath = TextUtils.isEmpty(dbCommonMessage.getLocalVideo()) ? dbCommonMessage.getVideo() : dbCommonMessage.getLocalVideo();
                    String thumbPath = TextUtils.isEmpty(dbCommonMessage.getLocalThumbPic()) ? dbCommonMessage.getThumbPic() : dbCommonMessage.getLocalThumbPic();

                    if (!tempData.isSender()) {
                        videoPath = dbCommonMessage.getVideo();
                        thumbPath = dbCommonMessage.getThumbPic();
                    }

                    dbMyMessage.setMediaFilePath(videoPath);
                    dbMyMessage.setThumbPic(thumbPath);
                    break;
                case MessageConstant.MSG_ID_GIFT:
                    imType = tempData.isSender() ? IMessage.MessageType.SEND_GIFT.ordinal() : IMessage.MessageType.RECEIVE_GIFT.ordinal();
                    dbMyMessage = new MyMessage(null, imType);
                    dbMyMessage.setGiftIcon(dbCommonMessage.getGiftIcon());
                    dbMyMessage.setGiftName(dbCommonMessage.getGiftName());
                    dbMyMessage.setGiftNum(dbCommonMessage.getGiftNum());
                    break;
            }
            if (dbMyMessage != null) {
                dbMyMessage.setUserInfo(tempData.isSender() ? sendUser : receiverUser);
                dbMyMessage.setMessageStatus(tempData.isSendFail() ? IMessage.MessageStatus.SEND_FAILED :
                        tempData.isSender() ? IMessage.MessageStatus.SEND_SUCCEED : IMessage.MessageStatus.RECEIVE_SUCCEED);
                mData.add(dbMyMessage);
            }
        }
        mAdapter.addToEndChronologically(mData);
        if (page == 1)
            mAdapter.getLayoutManager().scrollToPosition(0);
    }
    // ======================== OnMenuClickListener监听 ========================

    /**
     * 文本消息发送
     */
    @Override
    public boolean onSendTextMessage(CharSequence input) {
        if (input.length() == 0 || TextUtils.isEmpty(input.toString().trim()) || !sendPretreatment()) {
            return false;
        }
        sendMessage = new MyMessage(input.toString(), IMessage.MessageType.SEND_TEXT.ordinal());
        sendMessage.setUserInfo(sendUser);
        //message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
        sendMessage.setMessageStatus(IMessage.MessageStatus.SEND_GOING);
        mAdapter.addToStart(sendMessage, true);

        // 发送
        ModuleMgr.getChatMgr().sendTextMsg(whisperID, sendMessage.getText(), true, new SendCallBack() {
            @Override
            public void onResult(long msgId, long sender, String contents) {
                sendMessage.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onSendFailed(NetData data) {
                sendMessage.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                mAdapter.notifyDataSetChanged();
            }
        });
        return true;
    }

    /**
     * 文件消息发送
     */
    @Override
    public void onSendFiles(List<FileItem> list) {
        if (list == null || list.isEmpty() || !sendPretreatment()) return;

        picMsgList.clear();
        for (FileItem item : list) {
            if (item.getType() == FileItem.Type.Image) {
                picMsgList.add(item.getFilePath());
            } else if (item.getType() == FileItem.Type.Video) {
                PToast.showShort("暂时无法发送本地视频");
            } else {
                throw new RuntimeException("Invalid FileItem type. Must be Type.Image or Type.Video");
            }
        }
        loopSendPic();
    }

    @Override
    public void onSendVideo() {
        ModuleMgr.getRtcChatMgr().inviteVideo(IMActivity.this, whisperID);
    }

    @Override
    public void onSendVoice() {
        ModuleMgr.getRtcChatMgr().inviteVoice(IMActivity.this, whisperID);
    }

    private static final int VideoUploadResult = 10002;

    @Override
    public boolean switchToCameraMode() {
        if (sendPretreatment())
            MeetUIShow.showRecordVideoAct(IMActivity.this, VideoUploadResult);
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == VideoUploadResult) {     // 短视频录制
            if (resultCode == RESULT_OK) {
                String sVideo = data.getStringExtra(RecordVideoAct.EXTRA_RECORD_FILE_PATH);
                VideoUpload(sVideo);
            }
        }
    }

    @Override
    public boolean switchToMicrophoneMode() {
        return true;
    }

    @Override
    public boolean switchToGalleryMode() {
        PermissionUtil.checkStoragePermission(this, null);
        return true;
    }

    @Override
    public boolean switchToEmojiMode() {
        return true;
    }

    // =============================================== 图片发送 =========================================
    private List<String> picMsgList = new ArrayList<>();            // 维护多选图片发送顺序

    // 循环发送图片
    private void loopSendPic() {
        try {
            if (picMsgList.size() > 0) {
                picSend(picMsgList.remove(0));
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onUrl(String url) {
        picSend(url);
    }

    private void picSend(final String filePath) {
        sendMessage = new MyMessage(null, IMessage.MessageType.SEND_IMAGE.ordinal());
        sendMessage.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
        sendMessage.setMediaFilePath(filePath);
        sendMessage.setUserInfo(sendUser);
        runOnUiThread(() -> mAdapter.addToStart(sendMessage, true));

        final String smallPath = BitmapUtil.getSmallBitmapAndSave(filePath, DirType.getUploadDir());
        if (FileUtil.isExist(smallPath)) {
            ModuleMgr.getMediaMgr().sendHttpFile(MediaConstant.UPLOAD_TYPE_PIC, smallPath, response -> {
                FileUtil.deleteFile(smallPath);
                if (response.isOk()) {
                    UpLoadResult result = (UpLoadResult) response.getBaseData();
                    ModuleMgr.getChatMgr().sendPhotoMsg(whisperID, result.getUploadUrl(), new SendCallBack() {
                        @Override
                        public void onResult(long msgId, long sender, String contents) {
                            sendMessage.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                            mAdapter.notifyDataSetChanged();
                            loopSendPic();
                        }

                        @Override
                        public void onSendFailed(NetData data) {
                            sendMessage.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                            mAdapter.notifyDataSetChanged();
                            loopSendPic();
                        }
                    });
                }
            });
        } else {
            PToast.showShort("图片地址无效");
            loopSendPic();
        }
    }

    // =============================================== 小视频发送 =========================================
    private void VideoUpload(final String sPath) {
        final String thumbPic = Video.getVideoThumb(sPath);
        sendMessage = new MyMessage(null, IMessage.MessageType.SEND_VIDEO.ordinal());
        sendMessage.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
        sendMessage.setMediaFilePath(sPath);
        sendMessage.setThumbPic(thumbPic);
        sendMessage.setUserInfo(sendUser);
        runOnUiThread(() -> mAdapter.addToStart(sendMessage, true));

        if (FileUtil.isExist(thumbPic)) {
            ModuleMgr.getMediaMgr().sendHttpFile(MediaConstant.UPLOAD_TYPE_PIC, thumbPic, response -> {
                String resultThumb = "";
                if (response.isOk()) {
                    UpLoadResult result = (UpLoadResult) response.getBaseData();
                    resultThumb = result.getUploadUrl();
                }
                sendVideoMsg(sPath, sendMessage, resultThumb, thumbPic, "");
            });
        }
    }

    private void sendVideoMsg(final String sPath, final MyMessage message, final String thumb, final String localThumb, final String duration) {
        if (FileUtil.isExist(sPath)) {
            ModuleMgr.getMediaMgr().sendHttpFile(MediaConstant.UPLOAD_TYPE_VIDEO, sPath, response -> {
                if (response.isOk()) {
                    UpLoadResult result = (UpLoadResult) response.getBaseData();
                    ModuleMgr.getChatMgr().sendVideoMsg(whisperID, result.getUploadUrl(), sPath, thumb, localThumb, duration, new SendCallBack() {
                        @Override
                        public void onResult(long msgId, long sender, String contents) {
                            message.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                            mAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onSendFailed(NetData data) {
                            message.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
            });
        } else {
            LoadingDialog.closeLoadingDialog();
            PToast.showShort("文件地址无效");
        }
    }
    // =============================================== 小视频发送 end =========================================

    // 消息点击处理
    @Override
    public void onMessageClick(IMessage message) {
        int msgType = message.getType();
        // 视频消息
        if (msgType == IMessage.MessageType.SEND_VIDEO.ordinal() ||
                msgType == IMessage.MessageType.RECEIVE_VIDEO.ordinal()) {
            VideoPlayDialog playDialog = new VideoPlayDialog(this, message.getMediaFilePath());
            playDialog.show();
            return;
        }

        // 图片消息
        if (msgType == IMessage.MessageType.SEND_IMAGE.ordinal() ||
                msgType == IMessage.MessageType.RECEIVE_IMAGE.ordinal()) {
            MeetUIShow.showPhotoOfBigImg(this, message.getMediaFilePath());
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send_gift:
                if (ModuleMgr.getRtcEnginMgr().getEngineConfig().mJoinStatus) {  // 音视频聊天中
                    PToast.showShort("您当前处于音视频聊天中，不能发送礼物");
                    return;
                }
                ModuleMgr.getRtcEnginMgr().getEngineConfig().mVcid = 0;
                RtcUIShow.showRtcBottomGiftDlg(this, whisperID, false, this);
                break;
        }
    }

    @Override
    public void sendGiftSuccess(GiftsList.GiftInfo info) {
        sendMessage = new MyMessage(null, IMessage.MessageType.SEND_GIFT.ordinal());
        sendMessage.setGiftIcon(info.getPic());
        sendMessage.setGiftName(info.getName());
        sendMessage.setGiftNum(info.getNum());
        sendMessage.setUserInfo(sendUser);
        sendMessage.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
        mAdapter.addToStart(sendMessage, true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        queryCallback = null;
        MsgMgr.getInstance().sendMsg(MsgType.MT_MyInfo_Change, null);
        UnreadMgr.whisperId = 0;
        IMChatUtil.getInstance().setReceiveMsgListener(null);
        MsgMgr.getInstance().detach(this);
    }
}
